package pl.ciaastek.ubuntucontrol;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class Profiles extends ListActivity {
	private Context context = this;
	private ArrayList<String> results = new ArrayList<String>();
	private ListView lista = null;
	private ArrayAdapter<?> adapter = null;
	private SQLiteDatabase baza = null;
	private Cursor cursor = null;
	private String server_db, user_db, password_db, port_db;
	private EditText server, port, user, password;
	final static Connection conn = new Connection();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profiles);

		try {

			baza = this.openOrCreateDatabase("SERVERS", MODE_PRIVATE, null);

			baza.execSQL("CREATE TABLE IF NOT EXISTS Profiles (_id INTEGER PRIMARY KEY, Server VARCHAR, Username VARCHAR, Password VARCHAR, Port INT)");
			cursor = baza.rawQuery("SELECT * FROM Profiles", null);
			if (cursor.moveToFirst()) {
				do {
					String text_server = cursor.getString(cursor
							.getColumnIndex("Server"));
					String text_username = cursor.getString(cursor
							.getColumnIndex("Username"));
					results.add(text_username + "@" + text_server);
				} while (cursor.moveToNext());
			}
			this.lista = (ListView) findViewById(android.R.id.list);
			lista.setAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, results));

		} catch (SQLiteException e) {
			Log.e(getClass().getSimpleName(),
					"Could not create or Open the database");
		}
		baza.close();

		lista.setHapticFeedbackEnabled(true);

		lista.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				conn.intent = new Intent(context, Control.class);
				if (!cursor.moveToPosition(arg2))
					cursor = baza.rawQuery("SELECT * FROM Profiles", null);
				cursor.moveToPosition(arg2);
				server_db = cursor.getString(cursor.getColumnIndex("Server"));
				port_db = cursor.getString(cursor.getColumnIndex("Port"));
				user_db = cursor.getString(cursor.getColumnIndex("Username"));
				password_db = cursor.getString(cursor
						.getColumnIndex("Password"));

				conn.intent.putExtra("server", server_db);
				conn.intent.putExtra("port", port_db);
				conn.intent.putExtra("username", user_db);
				conn.intent.putExtra("password", password_db);

				new MakeConnection(context, conn).execute(server_db,
						String.valueOf(port_db), user_db, password_db);

				// startActivity(conn.intent);

			}
		});

		lista.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				AlertDialog.Builder dlg_remove = new AlertDialog.Builder(
						context);
				CharSequence dlg[] = { "Edytuj", "Usuń profil" };
				dlg_remove.setItems(dlg, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							break;
						case 1:
							baza = context.openOrCreateDatabase(
									conn.md5("SERVERS"), MODE_PRIVATE, null);
							cursor = baza.rawQuery("SELECT * FROM Profiles",
									null);
							cursor.moveToPosition(arg2);
							baza.execSQL("DELETE FROM Profiles WHERE _id="
									+ cursor.getString(cursor
											.getColumnIndex("_id")) + "");

							results.remove(arg2);
							context.deleteDatabase(conn.md5(results.get(arg2)));
							adapter = (ArrayAdapter<?>) lista.getAdapter();
							adapter.notifyDataSetChanged();
							break;
						}
					}
				});
				dlg_remove.show();

				return true;
			}
		});
	}

	public void addNew() {
		AlertDialog.Builder profile = new AlertDialog.Builder(this);
		LayoutInflater layout = LayoutInflater.from(this);
		final View view = layout.inflate(R.layout.profile_new_dialog, null);
		profile.setView(view);
		profile.setTitle("Dodaj profil");
		profile.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						server = (EditText) view
								.findViewById(R.id.dialog_server);
						port = (EditText) view
								.findViewById(R.id.dialog_server_port);
						user = (EditText) view
								.findViewById(R.id.dialog_username);
						password = (EditText) view
								.findViewById(R.id.dialog_password);
						server_db = server.getText().toString();
						port_db = port.getText().toString();
						user_db = user.getText().toString();
						password_db = password.getText().toString();
						baza = context.openOrCreateDatabase("SERVERS",
								MODE_PRIVATE, null);
						baza.execSQL("INSERT INTO Profiles('Server', 'Username','Password', 'Port') Values('"
								+ server_db
								+ "','"
								+ user_db
								+ "','"
								+ password_db + "','" + port_db + "');");
						results.add(user_db + "@" + server_db);
						adapter = (ArrayAdapter<?>) lista.getAdapter();
						adapter.notifyDataSetChanged();
						dialog.dismiss();
					}

				});

		profile.setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		profile.setCancelable(false);
		profile.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.profiles, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_profile:
			addNew();
			break;
		}
		return true;
	}
}
